<?php
/**
 * ActionCache.php
 *
 * @category    Madoqua
 * @package     Controller
 * @subpackage  Plugin
 */

/** base class */
require_once 'Zend/Controller/Plugin/Abstract.php';

/** action cache */
require_once 'Madoqua/Cache/Action.php';

/**
 * Madoqua_Controller_Plugin_ActionCache
 *
 * @category    Madoqua
 * @package     Controller
 * @subpackage  Plugin
 */
class Madoqua_Controller_Plugin_ActionCache extends Zend_Controller_Plugin_Abstract
{
    /**
     * the cache
     *
     * @var Zend_Cache_Core
     */
    protected $_cache;

    /**
     * body
     *
     * @var string
     */
    protected $_body = '';

    /**
     * do cache?
     *
     * @var bool
     */
    protected $_doCache = false;

    /**
     * cache id
     *
     * @var string
     */
    protected $_cacheId = '';

    /**
     * constructor
     */
    public function __construct() {
        $this->_cache = Madoqua_Cache_Action::get();
        //the action cache
    }

    /**
     * check whether this action has to be cached
     *
     * @param Zend_Controller_Request_Abstract $request
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        $this->_doCache = false;
        //let's assume we don't want caching

        if (Madoqua_Cache_Action::canCache()) {
            //caching is allowed, woo!

            if (!Madoqua_Cache_Action::hasCache($request)) {
                //no hit in cache, we're going to build one ourselves

                $this->_body = $this->getResponse()->getBody();
                //remember old body (should there be one)
                $this->getResponse()->clearBody();
                //clear the body
                $this->_doCache = true;
                //we are doing a cache run!
            } else {
                //don't execute action
                
                $this->_doCache = Madoqua_Cache_Action::loadCache($request);
                
                $request->setModuleName('front');
                $request->setControllerName('index');
                $request->setActionName('empty');
                //forward to empty action... ja... UGLY
                //FIXME really... fix this.
                
                
            }
        }
    }

    /**
     * postDispatch hook
     *
     * @param Zend_Controller_Request_Abstract $request
     */
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        if ($this->_doCache === true) {
            //we are doing a cache run!
            $result = $this->getResponse()->getBody();
            //body generated by action
            $this->getResponse()->setBody($this->_body . $result);
            //set the body right
            Madoqua_Cache_Action::saveCache($result, $request);
            //save the cached version
        } else {
            $this->getResponse()->setBody("/*cached*/" . $this->_doCache);          
        }
    }
}